package com.loiot.baqi.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.aliyun.oss.model.OSSObject;
import com.loiot.baqi.constant.URLConst;
import com.loiot.baqi.controller.response.AjaxResponse;
import com.loiot.baqi.service.DownloadService;
import com.loiot.baqi.utils.OSSUtils;

/**
 * 下载控制器
 * 
 * @author wangzx
 * 
 */
@Controller
@RequestMapping(value = "/download")
public class DownloadController {

    public static final AjaxResponse ACCOUNT_USERNAME_EXIST = new AjaxResponse(-100301, "用户名已存在");

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 下载业务逻辑
     */
    @Resource
    private DownloadService downloadService;
   
    /**下载序列号
     * @param response
     * @param pbId
     */
    @RequestMapping(value = "/file",method = RequestMethod.GET)
    public String downLoad(HttpServletResponse response,
    		@RequestParam(value="id",required=true) long id,
    		@RequestParam(value="type",required=true) int type){
            
    	try {
			downloadService.download(response, id, type);
		} catch (Exception e) {
			return URLConst.ERROR_URL;
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
    	return null;
    }
   
    /**下载序列号
     * @param response
     * @param pbId
     */
    @RequestMapping(value = "/picture/{url}", method = RequestMethod.GET)
    public void downLoad(@PathVariable(value="url") String url, HttpServletResponse response){
    	if(log.isDebugEnabled()) log.debug("Download file {}", url);
    	response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename="+url);
        response.setContentType("image/jpeg;charset=UTF-8");
        // 解决ie6下，保存错误问题
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public");
        OSSObject ossObject = OSSUtils.getObject(url);
        try {
			IOUtils.write(IOUtils.toByteArray(ossObject.getObjectContent()), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    }
    
}
